<?php
/**
 * Name: 判断账号是否被禁用.
 * User: 董坤鸿
 * Date: 2016/10/13
 * Time: 10:46
 */

namespace App\Http\Middleware;

use App\Models\Company;
use App\Services\HelpService;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Auth;

class Login
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Auth::User();
        $company = Company::withTrashed()->find($user->company_id);
        if (is_null($company)) {
            return view("errors.disable", ['time'=>5, 'msg'=>'账号非法']);
        }
        // 渠道时间到期, 禁止改渠道下账号登录 todo: 后期改为脚本
        $endDate = $company->endDate;
        if ($endDate != null) {
            $datetime = is_string($endDate) ? new Carbon($endDate) : $endDate->toDateTime();
            $datetime = strtotime($datetime->format('r'));
            if ($datetime < time()) {
                if (HelpService::fromApp()) {
                    abort(401, '使用时间到期');
                } else {
                    $session = $request->session();
                    $session->clear();
                    return view("errors.disable", ['time'=>5, 'msg'=>'使用时间到期']);
                }
            }
        }
        if ($user->status == 0 || (isset($company->deleted_at) && !is_null($company->deleted_at))) {
            if (HelpService::fromApp()) {
                abort(401, '您的账号已经被禁用');
            } else {
                $session = $request->session();
                $session->clear();
                return view("errors.disable", ['time'=>5, 'msg'=>'您的账号已经被禁用']);
            }
        }
        return $next($request);
    }
}
